<?php 
App::uses('AppController', 'Controller');

class RegisterUserController extends AppController {
	var $components = array('Strings');
	
	public function index() {
		
		$this->layout = 'layoutNoMenuLeft';
		$this->set("title_for_layout","Đăng ký thành viên");
		$this->loadModel('User');
		
	    //kiem tra login
	    if ($this->Auth->loggedIn()) {
			$this->redirect("/");
		}
		
		if ($this -> request -> is('post')) {
			$captcha = $this->Session->read('captcha_code');
			if ( $captcha == $this->request->data['captcha'] ){
				$new = $this -> request->data;
			// kiem tra trung user name , email
			if(!$this->User->isUniqueUsername($new) ||
					!$this->User->isUniqueEmail($data)){
				return;
			}
			$new['username'] = $this->Strings->replaceHTMLTag($new['username']);
			$new['group_id'] = GROUP_MEMBER;
			$new['deleted'] = 0;
			$new['created_by'] = 0;
			$new['created_at'] = date("Y-m-d H:i:s");
			$new['updated_by'] = 0;
			$new['updated_at'] = date("Y-m-d H:i:s");
			// lưu thành công
			if($this->User->save($new)){
				$id = $this->User->id;
				$user = $this->User->find("first",array('conditions' => array('User.id' => $id)));
				if($this->Auth->login($user['User'])){
					$this->redirect('/Member/manage');
				}
			}
			}else{
				$this->Session->setFlash(__('Captcha code does not match. Verification unsuccessful'));
			}
			
			
		}
		
	}
	public function checkUserNameAndEmail(){
		$this->loadModel('User');
		$arr = array();
		$arr['err']= array("val"=>"0");
		if ($this -> request -> is('post')) {
			$data = $this -> request ->data;
			if(!$this->User->isUniqueUsername($data)){
				$arr['name']= array("userName"=>"Vui lòng chọn tên khác");
				$arr['err']= array("val"=>"1");
			}
			if(!$this->User->isUniqueEmail($data)){
				$arr['email']= array("userEmail"=>"Email này đã được sử dụng");
				$arr['err']= array("val"=>"1");
			}
			echo json_encode($arr);
		}else{
			echo json_encode(array('err'=>'2', 'msg'=>"Không hợp lệ"));
		}
		exit;
	}	
}
?>